package carcassonne.server.http;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.*;

import java.nio.charset.StandardCharsets;

public class HttpContext {

    public HttpRequest request;

    public FullHttpResponse response = null;

    private String Content = null;

    public HttpContext(HttpRequest request) {
        this.request = request;
    }

    public void SetContent(String content) {
        Content = content;
    }

    public void ResponseOK() {
        DoResponse(HttpResponseStatus.OK);
    }

    public void ResponseOK(Object message) {
        DoResponse(HttpResponseStatus.OK, JSON.toJSONString(message));
    }

    public void ResponseOK(String message) {
        DoResponse(HttpResponseStatus.OK, message);
    }

    public void ResponseForbidden() {
        DoResponse(HttpResponseStatus.FORBIDDEN);
    }

    public void ResponseForbidden(String message) {
        DoResponse(HttpResponseStatus.FORBIDDEN, message);
    }

    public void Response404() {
        DoResponse(HttpResponseStatus.NOT_FOUND);
    }

    public void Response404(String message) {
        DoResponse(HttpResponseStatus.NOT_FOUND, message);
    }

    private void DoResponse(HttpResponseStatus status) {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
    }

    private void DoResponse(HttpResponseStatus status, String message) {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
                Unpooled.wrappedBuffer(message.getBytes(StandardCharsets.UTF_8)));
    }

    public void Finish() {
        if (response == null) {
            if (Content == null) {
                response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            } else {
//                response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(Content.getBytes(StandardCharsets.UTF_8)));
                response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(Content.getBytes()));
            }
        }
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/json;charset=utf-8");
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    }
}
